"use client"

import { useEffect, useState } from "react"
import Image from "next/image"
import { Button } from "@/components/ui/button"
import { EditProfileButton } from "@/components/edit-profile-button"
import { getUserProfile } from "@/lib/api-client"
import {
  getUserLikedSongs,
  getUserLikedAlbums,
  getUserLikedMVs,
  getUserLikedPlaylists,
  getUserFollowing,
  getUserFollowers,
} from "@/lib/api-client"
import { ProfileTabs } from "@/components/profile/profile-tabs"
import { Skeleton } from "@/components/ui/skeleton"
import {Album, MV, Playlist, Song, UserFollower, UserFollowing} from "@/types";
import {useRouter} from "next/navigation";

export default function MyProfilePage() {
  const [isLoading, setIsLoading] = useState(true)
  const [profile, setProfile] = useState<any>(null)
  const [likedSongs, setLikedSongs] = useState<Song[]>([])
  const [likedAlbums, setLikedAlbums] = useState<Album[]>([])
  const [likedMVs, setLikedMVs] = useState<MV[]>([])
  const [likedPlaylists, setLikedPlaylists] = useState<Playlist[]>([])
  const [createdPlaylists, setCreatedPlaylists] = useState<Playlist[]>([])
  const [following, setFollowing] = useState<UserFollowing[]>([])
  const [followers, setFollowers] = useState<UserFollower[]>([])
  const [error, setError] = useState<string | null>(null)
  const router = useRouter();
  useEffect(() => {
    async function fetchData() {
      try {
        // In a real app, we would get the current user's ID from the session
        const userId: string = localStorage.getItem("userId") as string
        if (!userId){
          router.push("/login")
          setIsLoading(false)
          return null;  // 在跳转过程中不渲染任何内容
        }
        // Fetch profile data first
        const profileResponse = await getUserProfile(userId)
        setProfile(profileResponse.data)

        // Fetch other data concurrently
        const [
          likedSongsResponse,
          likedAlbumsResponse,
          likedMVsResponse,
          likedPlaylistsResponse,
          createdPlaylistsResponse,
          followingResponse,
          followersResponse,
        ] = await Promise.all([
          getUserLikedSongs({ userId, limit: 10 }),
          getUserLikedAlbums({ userId, limit: 10 }),
          getUserLikedMVs({ userId, limit: 10 }),
          getUserLikedPlaylists({ userId, limit: 10 }),
          getUserLikedPlaylists({ userId, limit: 10, created: true }),
          getUserFollowing({ userId, limit: 10 }),
          getUserFollowers({ userId, limit: 10 }),
        ])

        setLikedSongs(likedSongsResponse.data)
        setLikedAlbums(likedAlbumsResponse.data)
        setLikedMVs(likedMVsResponse.data)
        setLikedPlaylists(likedPlaylistsResponse.data)
        setCreatedPlaylists(createdPlaylistsResponse.data)
        setFollowing(followingResponse.data)
        setFollowers(followersResponse.data)

        setIsLoading(false) // 确保在所有数据加载完之后再设置 isLoading 为 false
      } catch (err) {
        console.error("拉取我的音乐数据失败：", err)
        setError("加载数据失败 请稍后再试！")
        setIsLoading(false)
      }
    }
    fetchData()
  }, [])

  if (error) {
    return (
        <div className="container py-10">
          <div className="text-center">
            <h1 className="text-2xl font-bold text-red-500">Error</h1>
            <p className="text-muted-foreground">{error}</p>
            <Button onClick={() => window.location.reload()} className="mt-4">
              重试
            </Button>
          </div>
        </div>
    )
  }
  if (!isLoading && profile){
  return (
      <div className="container pb-10">
        {/* Profile Header */}
        <div className="relative">
          <div className="h-48 w-full overflow-hidden rounded-b-md sm:h-64">
            {isLoading ? (
                <Skeleton className="h-full w-full" />
            ) : (
                <Image
                    src={profile?.cover || "/placeholder.svg?height=256&width=1024"}
                    alt="Cover"
                    fill
                    className="object-cover"
                    priority
                />
            )}
          </div>
          <div className="absolute -bottom-16 left-4 h-32 w-32 overflow-hidden rounded-full border-4 border-background sm:-bottom-20 sm:h-40 sm:w-40">
            {isLoading ? (
                <Skeleton className="h-full w-full rounded-full" />
            ) : (
                <Image
                    src={profile?.avatar || "/placeholder.svg?height=160&width=160"}
                    alt={profile?.username || "User"}
                    fill
                    className="object-cover"
                    priority
                />
            )}
          </div>
          {!isLoading && (
              <div className="absolute right-4 top-4">
                <EditProfileButton profile={profile} />
              </div>
          )}
        </div>

        {/* Profile Info */}
        <div className="mt-20 sm:mt-24">
          <div className="flex flex-col gap-1 pl-4">
            {isLoading ? (
                <>
                  <Skeleton className="h-8 w-48" />
                  <Skeleton className="h-4 w-64 mt-2" />
                  <div className="mt-3 flex gap-4">
                    <Skeleton className="h-5 w-20" />
                    <Skeleton className="h-5 w-20" />
                  </div>
                </>
            ) : (
                <>
                  <h1 className="text-2xl font-bold">{profile?.username}</h1>
                  <p className="text-muted-foreground">{profile?.bio || "No bio yet."}</p>
                  <div className="mt-1 flex gap-4 text-sm text-muted-foreground">
                    <div>
                      <span className="font-medium text-foreground">{profile?.stats?.followingCount || 0}</span> 关注
                    </div>
                    <div>
                      <span className="font-medium text-foreground">{profile?.stats?.followersCount || 0}</span> 粉丝
                    </div>
                  </div>
                </>
            )}
          </div>
        </div>

        {/* Profile Content */}
        <div className="mt-8">
          <ProfileTabs
              likedSongs={likedSongs}
              likedAlbums={likedAlbums}
              likedPlaylists={likedPlaylists}
              likedMVs={likedMVs}
              createdPlaylists={createdPlaylists}
              following={following}
              followers={followers}
              isLoading={isLoading}
          />
        </div>
      </div>
  )
}
}

